<template>
  <el-drawer
    v-model="state.visible"
    size="50%"
    destroy-on-close
    :title="$t('marking_labelFees.add_payment')"
    @closed="handleClose"
  >
    <div class="label-fees-drawer">
      <div class="label-fees-drawer-content">
        <el-scrollbar>
          <el-form ref="formRef" label-position="top" :model="state.data" :rules="addFormRules">
            <el-row :gutter="40">
              <el-col :span="12">
                <el-form-item prop="payment_date" :label="$t('marking_labelFees.payment_date')">
                  <el-date-picker v-model="state.data.payment_date" class="qf_date" value-format="YYYY-MM-DD" :format="format" />
                </el-form-item>
              </el-col>
              <el-col v-if="!props.currency" :span="12">
                <el-form-item prop="supplier_id" :label="$t('marking_labelFees.supplier_id')">
                  <el-select
                    v-model="state.data.supplier_id"
                    class="qf_select"
                    filterable
                    remote
                    remote-show-suffix
                    :remote-method="handleRemoteSupplier"
                    :placeholder="$t('marking_labelFees.supplier_id_placeholder')"
                    @change="handleQueryOptionsBySupplier"
                  >
                    <el-option v-for="option in state.supplier" :value="option.value" :label="option.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="!props.currency" :span="12">
                <el-form-item prop="payment_currency" :label="$t('marking_labelFees.payment_currency')">
                  <el-select v-model="state.data.payment_currency" class="qf_select" filterable @change="handleQueryOptions">
                    <el-option v-for="option in state.currency" :value="option.value" :label="option.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="payment_amount" :label="$t('marking_labelFees.payment_amount')">
                  <el-input v-model="state.data.payment_amount" v-num.point class="qf_input" :maxlength="200">
                    <template v-if="!!currencyType" #prefix>
                      {{ currencyType }}
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="payment_type" :label="$t('marking_labelFees.payment_type')">
                  <el-select
                    v-model="state.data.payment_type"
                    class="qf_select"
                    filterable
                    :disabled="!props.currency && !state.data.payment_currency"
                  >
                    <el-option v-for="option in optionMap.payment_type" :value="option.value" :label="option.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="payer" :label="$t('marking_labelFees.payer')">
                  <el-autocomplete v-model="state.data.payer" class="qf_input" clearable :fetch-suggestions="querySearchPayer" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="payee" :label="$t('marking_labelFees.payee')">
                  <el-autocomplete v-model="state.data.payee" class="qf_input" clearable :fetch-suggestions="querySearchPayee" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="operator" :label="$t('marking_labelFees.operator')">
                  <el-select
                    v-model="state.data.operator"
                    class="qf_select"
                    filterable
                    remote-show-suffix
                    :remote="optionMap.operator.length > 50"
                    :remote-method="handleRemoteOperator"
                    :placeholder="optionMap.operator.length > 50 ? $t('marking_labelFees.operator_placeholder') : undefined"
                  >
                    <el-option
                      v-for="option in optionMap.operator.length > 50 ? state.operator : optionMap.operator"
                      :value="option.value"
                      :label="option.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="pay_factory_id" :label="$t('marking_labelFees.pay_factory_id')">
                  <el-select
                    v-model="state.data.pay_factory_id"
                    class="qf_select"
                    filterable
                    remote-show-suffix
                    :remote="optionMap.pay_factory_id.length > 50"
                    :remote-method="handleRemoteFactory"
                    :disabled="!props.currency && !state.data.supplier_id"
                    :placeholder="
                      optionMap.pay_factory_id.length > 50 ? $t('marking_labelFees.pay_factory_id_placeholder') : undefined
                    "
                  >
                    <el-option
                      v-for="option in optionMap.pay_factory_id.length > 50 ? state.pay_factory_id : optionMap.pay_factory_id"
                      :value="option.value"
                      :label="option.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="remark" :label="$t('marking_labelFees.remark')">
                  <el-input v-model="state.data.remark" class="qf_input" :maxlength="200" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-scrollbar>
      </div>
      <div class="label-fees-drawer-handle">
        <el-button @click="state.visible = false">{{ $t("merak.cancel") }}</el-button>
        <el-button v-if="!props.data" type="primary" plain :loading="state.resetLoading" @click="handleSave(true)">
          {{ $t("merak.save_continue") }}
        </el-button>
        <el-button type="primary" :loading="state.loading" @click="handleSave()">{{ $t("merak.save") }}</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import type { LabelFeesType } from "../index";

import { getCurrentInstance, toRef, ref, reactive, computed, watch, watchEffect, onMounted } from "vue";

import { useRoute } from "vue-router";

import useDateFormat from "@/hooks/useDateFormat";

import {
  FormRules,
  ElDrawer,
  ElScrollbar,
  ElButton,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElInput,
  ElAutocomplete,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage
} from "element-plus";

import { ResultEnum } from "@/enums/httpEnum";
import { OptionType, getSelectOptions, createPayment, savePayment } from "@/api/modules/markingManagement/labelFees";

import { confirmWarningMsg } from "@/utils/messageUtils";

interface OptionMapType {
  // 商家
  supplier: OptionType[];
  // 经手人
  operator: OptionType[];
  // 付款方式
  payment_type: OptionType[];
  // 收付款方
  payer: OptionType[];
  // 付款方
  payee: OptionType[];
  // 贴标工厂
  pay_factory_id: OptionType[];
}

const props = defineProps<{
  // 币种
  currency?: LabelFeesType;
  // 编辑数据
  data?: Record<string, any> | null;
  // 有商家的下拉选项集合
  optionGroup?: Record<string, OptionType[]>;
}>();

const emits = defineEmits<{
  close: [saved: boolean];
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const { format } = useDateFormat();

const formRef = ref<InstanceType<typeof ElForm>>();

// 添加表单弹窗相关属性
const state = reactive<
  {
    data: Record<string, any>;
    saved: boolean;
    visible: boolean;
    loading: boolean;
    resetLoading: boolean;
    currency: OptionType[];
  } & Omit<OptionMapType, "payment_type" | "payer" | "payee">
>({
  data: {},
  saved: false,
  visible: false,
  loading: false,
  resetLoading: false,
  supplier: [],
  operator: [],
  pay_factory_id: [],
  currency: [
    { value: 4, label: "CNY" },
    { value: 1, label: "RUB" },
    { value: 2, label: "USD" }
  ]
});

// 初始化选项映射
const optionMap = reactive<OptionMapType>({
  supplier: [],
  operator: [],
  payment_type: [],
  payer: [],
  payee: [],
  pay_factory_id: []
});

// 表单校验规则
const addFormRules = computed<FormRules>(() => ({
  payment_date: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.payment_date_valid") }],
  supplier_id: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.supplier_id_valid") }],
  payment_currency: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.payment_currency_valid") }],
  payment_amount: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.payment_amount_valid") }],
  // payment_amount: [
  //   {
  //     required: true,
  //     validator: (rule, value, callback) => {
  //       console.log(value, value?.length, typeof value, !!value);

  //       if (!!value) {
  //         callback();
  //       } else {
  //         callback(new Error(""));
  //       }
  //     }
  //   }
  // ],
  payment_type: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.payment_type_valid") }],
  operator: [{ required: true, message: currentInstance?.proxy?.$t("marking_labelFees.operator_valid") }]
}));

// 币种类型
const currencyType = computed(() => {
  const currencyMap = {
    1: "₽",
    2: "$",
    4: "¥"
  };
  return currencyMap[props.currency ?? state.data.payment_currency];
});

// 关闭弹窗
const handleClose = () => {
  emits("close", state.saved);
  if (state.saved) {
    state.saved = false;
  }
};

// 表单提交
const handleSave = (reset: boolean = false) => {
  formRef.value?.validate().then(() => {
    confirmWarningMsg({
      msg: currentInstance?.proxy?.$t("marking_labelFees.save_pay_message") ?? "",
      callback: (status: string) => {
        if (status === "confirm") {
          if (reset) {
            state.resetLoading = true;
          } else {
            state.loading = true;
          }
          const params: Record<string, any> = { ...state.data };
          if (!!props.currency) {
            Object.assign(params, {
              supplier_id: route.query.id,
              currency: props.currency,
              payment_amount: (params.payment_amount as string).replace(" ", "")
            });
          }
          // @ts-ignore
          (!!props.currency ? savePayment : createPayment)(params).then(({ code, message }) => {
            if (reset) {
              state.resetLoading = false;
            } else {
              state.loading = false;
            }
            if (code == ResultEnum.SUCCESS) {
              state.saved = true;
              if (reset) {
                formRef.value?.resetFields();
              } else {
                state.visible = false;
              }
              ElMessage.success(currentInstance?.proxy?.$t("marking_labelFees.save_pay_success"));
            } else {
              const msg = typeof message === "object" ? Object.values(message)?.[0] : message;
              ElMessage.error(msg);
            }
          });
        }
      }
    });
  });
};

// 币种选项联动
const handleQueryOptions = (value: string | number) => {
  // 付款方式
  getSelectOptions({ type: "payment_type", value }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      optionMap.payment_type = [...(data.payment_type ?? [])];
    }
  });
};

// 商家联动
const handleQueryOptionsBySupplier = (value: string | number) => {
  getSelectOptions({ type: "payer_payee", value }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      optionMap.payer = [...(data.payerPayee?.payer ?? [])];
      optionMap.payee = [...(data.payerPayee?.payer ?? [])];
    }
  });
  getSelectOptions({ type: "pay_factory_id", value }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      optionMap.pay_factory_id = [...(data.pay_factory_id ?? [])];
    }
  });
  formRef.value?.resetFields(["pay_factory_id"]);
};

// 商家检索
const handleRemoteSupplier = (query: string) => {
  state.supplier = !!query ? optionMap.supplier.filter(option => option.label.toLowerCase().includes(query.toLowerCase())) : [];
};

// 经手人检索
const handleRemoteOperator = (query?: string) => {
  const defaultOption = optionMap.operator.find(option => option.value === state.data.operator);
  state.operator = !!query
    ? optionMap.operator.filter(option => option.label.toLowerCase().includes(query.toLowerCase()))
    : !!defaultOption
      ? [defaultOption]
      : [];
};

// 工厂检索
const handleRemoteFactory = (query: string) => {
  state.pay_factory_id = !!query
    ? optionMap.pay_factory_id.filter(option => option.label.toLowerCase().includes(query.toLowerCase()))
    : [];
};

// 付款方检索
const querySearchPayer = (query: string, callback: Function) => {
  const options = !!query ? optionMap.payer.filter(option => option.label.toLowerCase().includes(query.toLowerCase())) : [];
  callback(options);
};

// 收款方检索
const querySearchPayee = (query: string, callback: Function) => {
  const options = !!query ? optionMap.payee.filter(option => option.label.toLowerCase().includes(query.toLowerCase())) : [];
  callback(options);
};

watch(
  () => props.data,
  value => {
    if (!props.currency) return;
    state.data = !!value ? { ...value } : {};
    handleRemoteOperator();
  },
  { deep: true }
);

watchEffect(() => {
  const external = { ...(props.optionGroup ?? {}) };
  delete external.operator;
  Object.assign(optionMap, external);
});

onMounted(() => {
  if (!props.currency) {
    // 无商家
    getSelectOptions({ type: "supplier" }).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        optionMap.supplier = [...(data.supplier ?? [])];
      }
    });
  }
  // 经手人
  getSelectOptions({ type: "operator" }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      optionMap.operator = [...(data.operator ?? [])];
    }
  });
});

// 暴露表单弹窗打开的方法
defineExpose({
  open: () => Object.assign(state, { data: {}, visible: true })
});
</script>

<style scoped lang="scss">
.label-fees-drawer {
  display: flex;
  flex-direction: column;
  height: 100%;
  &-content {
    flex: 1;
    min-height: 0;
    :deep(.el-form-item__content > *) {
      width: 100%;
    }
    :deep(.el-input__prefix > .el-input__prefix-inner) {
      margin-top: -4px;
      margin-right: 4px;
      line-height: 1;
      font-size: var(--merak-text-size);
      font-style: normal;
    }
  }
  &-handle {
    margin-top: var(--merak-padding);
    text-align: right;
  }
}
</style>
